﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ActivitiesControl.Domain.Utils;
using ActivitiesControl.Domain.Entities;
using ActivitiesControl.Domain.Services;
using System.Threading;
using System.ComponentModel;

namespace ActivitiesControl.Async
{
	public class AsyncActivityServices
	{
		private IActivityServices service;
		private readonly SynchronizationContext syncContext;

		public event Action<IEnumerable<Activity>> ActivitiesRetrieved;
		public event EventHandler AsyncCallStarted;
		
		public AsyncActivityServices(IActivityServices service)
		{
			this.service = service;
			this.syncContext = AsyncOperationManager.SynchronizationContext;
		}
		
		public void BeginGetActivities(int resourceId, Date begin, Date end, int projectId)
		{
			AsyncCallStarted(this, null);
			AsyncCallback callback = EndGetActivities;
			Func<int, Date, Date, int, IEnumerable<Activity>> @delegate = service.GetActivities;
			@delegate.BeginInvoke(resourceId, begin, end, projectId, callback, @delegate);
		}

		private void EndGetActivities(IAsyncResult ar)
		{
			Func<int, Date, Date, int, IEnumerable<Activity>> @delegate = ar.AsyncState as Func<int, Date, Date, int, IEnumerable<Activity>>;
			IEnumerable<Activity> result = @delegate.EndInvoke(ar);
			//ActivitiesRetrieved(result);
			syncContext.Post((obj) => ActivitiesRetrieved(result), null);
		}
	}
}